<template>
    <div class="orderContent">
        <div class="addrRow" @click="handleShowAddr()">
            <p>
                收货人：<label>{{formData.receiver || '-'}}</label>
                手机号：<label>{{formData.receiverContact || '-'}}</label>
            </p>
            <p>
                详细地址：<label>{{formData.showAddr || '-'}}</label>
            </p>
            <van-icon name="arrow" size="16" />
        </div>
        <div class="orderRow">
            <div v-for="(item, index) in orderList" :key="item.rowId" class="list-item" :class="item.type === 'canteen' ? 'list-head' : ''">
                <div v-if="item.type === 'canteen'" class="flexRow head">
                    <p><b>{{item.canteenName}}</b>（ {{item.cookbookDate}} ）</p>
                    <span>{{item.mealsTypeName}}</span>
                </div>
                <div v-else class="flexRow">
                    <img :src="fileUrlObj[item.filecode] || (loading ? 'images/loading.gif' : 'images/noImgData.png')">
                    <div class="con">
                        <div class="dishName">{{item.dishName}}</div>
                        <div class="price">￥{{item.discountPrice}}</div>
                        <div class="number">x {{item.dishNum}}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="remarkRow">
            <van-field v-model="formData.remark" rows="3" label="备注" type="textarea" maxlength="256" placeholder="请输入备注" show-word-limit />
        </div>
        <div class="bottomTip">
            <van-submit-bar :price="totalPrice * 100" :suffix-label="'共' + totalNum + '件'" button-text="提交订单" @submit="handlePlaceOrder">
            </van-submit-bar>
        </div>
        <div class="result" v-if="showResult">
            <div class="close" @click="handleAllClose()">
                <van-icon name="cross" size="20" />
            </div>
            <div v-if="isSuccess" class="isSuccess">
                <van-icon size="100" name="checked" />
                <p>购买成功<span>（ 页面 {{closeTime}} 秒后将自动关闭 ）</span></p>
                <div>
                    <a @click="jumpMyOrder()">去我的订单 >></a>
                </div>
            </div>
            <div v-else class="isFail">
                <van-icon size="100" name="clear" />
                <p>购买失败<span>（ 页面 {{closeTime}} 秒后将自动关闭 ）</span></p>
                <div>
                    <a @click="jumpMyOrder()">去我的订单 >></a>
                </div>
                <ul class="msg" v-if="failMsg.config || failMsg.settlement || failMsg.payFail">
                    <li v-if="failMsg.config">
                        <label>食堂未配置：</label>
                        <span>{{failMsg.config}}</span>
                    </li>
                    <li v-if="failMsg.settlement">
                        <label>支付中心未配置：</label>
                        <span>{{failMsg.settlement}}</span>
                    </li>
                    <li v-if="failMsg.payFail">
                        <label>支付失败：</label>
                        <span v-html="failMsg.payFail"></span>
                    </li>
                </ul>
            </div>
        </div>
        <full-loading v-if="spinLoading"></full-loading>
        <fullscreenModal :modal="showAddrModal" label="我的收货地址" :isShowEdit="false" :showSave="false" editType="rightClose" @handleClose="showAddrModal = false">
            <addrList ref="addrRef" @setAddr="setAddr" />
        </fullscreenModal>
        <!-- 支付弹出层 -->
        <confirmOrder ref="payment" @paySuccess="paySuccess" @payCancel="handleClose()" :money="payMoney" />
    </div>
</template>

<script>
    import { queryFileList } from '@/api/common';
    import { addPlaceOrder, payment } from '@/api/srvAssurance/smarcatering/takeawayOrder';
    import addrList from './addrList';
    import confirmOrder from '@/components/confirmOrder';
    import { queryPersonPayment } from '@/api/platframe/mainFrame/pay';

    export default {
        name: 'payComp',
        components: { addrList, confirmOrder },
        data () {
            return {
                showResult: false,
                loading: false,
                spinLoading: false,
                showAddrModal: false,
                closeTime: 10,
                totalPrice: 0,
                totalNum: 0,
                orderList: [],
                fileUrlObj: {},
                formData: {
                    addrId: '',
                    receiver: '',
                    receiverContact: '',
                    detailAddr: '',
                    remark: ''
                },
                isSuccess: true,
                failMsg: {
                    config: '',
                    settlement: '',
                    payFail: ''
                },
                payMoney: '',
                paymentData: {}
            }
        },
        methods: {
            // 获取订单数据
            getOrderData (data) {
                this.$nextTick(() => {
                    this.$refs.addrRef.queryAddrListData();
                })
                this.formData = {
                    addrId: '',
                    receiver: '',
                    receiverContact: '',
                    detailAddr: '',
                    remark: ''
                }
                this.payMoney = '0';
                this.paymentData = {};
                this.totalPrice = 0;
                this.totalNum = 0
                this.orderList = [];
                let filecodeArr = [];
                data.forEach(item => {
                    this.orderList.push({
                        type: 'canteen',
                        ...item
                    })
                    item.data.forEach(val => {
                        this.orderList.push({
                            type: 'dish',
                            ...val
                        });
                        if (val.filecode && !this.fileUrlObj[val.filecode]) {
                            filecodeArr.push(val.filecode);
                            this.fileUrlObj[val.filecode] = '';
                        }
                        this.totalNum++;
                        this.totalPrice += (val.dishNum * val.discountPrice);
                    })
                })
                if (filecodeArr.length) {
                    this.queryFileInfoData(filecodeArr);
                }
            },
            // 设置收货地址
            setAddr (item) {
                this.formData.addrId = item.addrId;
                this.formData.receiver = item.receiver;
                this.formData.receiverContact = item.receiverContact;
                this.formData.showAddr = item.showAddr;

                if (this.showAddrModal) {
                    this.showAddrModal = false;
                }
            },
            // 提交订单
            handlePlaceOrder () {
                if (this.formData.remark && !this.$commonReg.textAreaReg.test(this.formData.remark)) {
                    this.$Notify({ type: 'warning', message: `备注${this.$commonReg.textAreaMsg}` });
                    return;
                }
                if (!this.formData.addrId) {
                    this.$Notify({ type: 'warning', message: '请选择收货地址' });
                    return;
                }
                let listCarts = []
                this.orderList.forEach(item => {
                    if (item.type === 'dish' && item.cartId) {
                        listCarts.push(item.cartId);
                    }
                })
                this.failMsg = {
                    config: '',
                    settlement: '',
                    payFail: ''
                }
                let params = {
                    listCarts,
                    loginTerminal: "app",
                    addrId: this.formData.addrId,
                    remake: this.formData.remark
                }
                this.spinLoading = true;
                addPlaceOrder(params).then(res => {
                    this.spinLoading = false;
                    if (res.code === 1000) {
                        if (res.data.code === '1') { // 线上支付
                            this.payMoney = res.data.amount ? (res.data.amount + '') : (this.totalPrice + '');
                            this.paymentData = res.data.data;
                            this.handlePaymentCheck();
                        } else if (res.data.code === '2') { // 线下支付
                            this.showResultFun(true);
                        }
                    }
                }).catch(() => {
                    this.spinLoading = false;
                })
            },
            // 支付校验
            handlePaymentCheck () {
                this.$refs.payment.isProof();
                // let staffId = sessionStorage.getItem("userid");
                // this.spinLoading = true;
                // queryPersonPayment({ staffId }).then(res => {
                //     if (res.code === 1000 && res.data) {
                //         if (res.data.payment_free === "1") { // 免密支付
                //             this.paySuccess();
                //         } else { // 密码校验
                //             this.spinLoading = false;
                //             this.$refs.payment.showModel = true;
                //         }
                //     } else {
                //         this.spinLoading = false;
                //     }
                // }).catch(() => {
                //     this.spinLoading = false;
                // })
            },
            // 支付成功
            paySuccess () {
                this.spinLoading = true;
                payment(this.paymentData).then(_res => {
                    this.spinLoading = false;
                    if (_res.code === 1000) {
                        if (_res.data.code === '1') { // 支付成功
                            this.showResultFun(true);
                        } else { // 订单有问题
                            if (_res.data.data) {
                                let _data = _res.data.data;
                                let payFailArr = [];
                                if (_data.payFailList && _data.payFailList.length) {
                                    _data.payFailList.forEach(v => {
                                        payFailArr.push(`<p>订单 ${v.orderNo}<span style="margin-left: 15px;color: red;">失败原因：</span>${v.msg || '无'}</p>`);
                                    })
                                }
                                this.failMsg = {
                                    config: _data.configList ? _data.configList.join("，") : '',
                                    settlement: _data.settlementList ? _data.settlementList.join("，") : '',
                                    payFail: payFailArr.join("")
                                }
                            }
                            this.showResultFun(false);
                        }
                    } else {
                        this.showResultFun(false);
                    }
                }).catch(() => {
                    this.spinLoading = false;
                })
            },
            showResultFun (flag) {
                this.closeTime = 10;
                this.showResult = true;
                this.isSuccess = flag;
                let timer = setInterval(() => {
                    this.closeTime--;
                    if (this.closeTime <= 0 || !this.showResult) {
                        clearInterval(timer);
                        if (this.showResult) {
                            if (this.isSuccess) { // 订单成功，关闭购物车
                                this.handleAllClose();
                            } else { // 订单失败，返回购物车
                                this.handleClose();
                            }
                        }
                    }
                }, 1000)
            },
            // 关闭结果
            handleClose () {
                this.showResult = false;
                this.$emit('close');
                this.$emit('refresh');
            },
            handleAllClose () {
                this.showResult = false;
                this.$emit('closeAll');
            },
            // 去我的订单页面
            jumpMyOrder () {
                this.$router.push({ name: 'smarcatering-myOrder' });
            },
            // 获取图片信息
            queryFileInfoData (filecodeArr) {
                this.loading = true;
                queryFileList(filecodeArr).then(res => {
                    if (res.code === 1000 && res.data) {
                        res.data.forEach(item => {
                            this.fileUrlObj[item.fileCode] = item.url;
                        })
                        this.$forceUpdate();
                        this.loading = false;
                    }
                }).catch(() => {
                    this.loading = false;
                })
            },
            // 查看更多收货地址
            handleShowAddr () {
                this.$refs.addrRef.initData();
                this.showAddrModal = true;
            }
        }
    }
</script>

<style scoped lang="less">
    .remarkRow {
        background: #fff;
        margin-top: 8px;
        /deep/.van-cell__title {
            width: 50px;
        }
    }
    .addrRow {
        background: #fff;
        position: relative;
        padding: 8px 30px 8px 8px;
        box-sizing: border-box;
        color: #999;
        font-size: 12px;
        line-height: 20px;
        p {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        label {
            color: #333;
            margin-right: 8px;
        }
        .van-icon {
            position: absolute;
            right: 5px;
            top: 50%;
            transform: translateY(-50%);
        }
    }
    .orderContent {
        padding: 8px;
        height: calc(100% - 46px);
        overflow: auto;
        background: #eee;
        box-sizing: border-box;
        .list-item {
            background: #fff;
            padding: 8px 8px 0 8px;
            box-sizing: border-box;
            & > .flexRow {
                padding-bottom: 8px;
            }
        }
        .list-head {
            margin-top: 8px;
        }
        img {
            width: 80px;
            height: 80px;
            margin: 0 8px;
        }
        .flexRow {
            display: flex;
            .con {
                flex: 1;
                overflow: hidden;
            }
        }
        .head {
            font-size: 12px;
            padding: 0 !important;
            justify-content: space-between;
            p {
                flex: 1;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                max-width: 200px;
                b {
                    font-size: 14px;
                }
            }
            span {
                margin-left: 10px;
            }
        }
        .dishName {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .price {
            text-align: right;
            color: rgb(242, 36, 36);
            line-height: 30px;
        }
        .number {
            font-size: 11px;
            color: #aaa;
            text-align: right;
        }
    }
    .bottomTip {
        .van-submit-bar__suffix-label {
            font-size: 11px;
            color: #aaa;
            float: left;
            line-height: 28px;
        }
        .van-submit-bar__button {
            width: auto;
        }
    }
    .result {
        position: fixed;
        background: #fff;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        text-align: center;
        z-index: 999;
        padding-top: 120px;
        p {
            line-height: 80px;
            font-size: 16px;
            font-weight: bold;
            span {
                font-size: 13px;
                color: #aaa;
            }
        }
        .close {
            position: absolute;
            right: 15px;
            top: 15px;
            cursor: pointer;
        }
        .isFail {
            color: #ed4014;
        }
        .isSuccess {
            color: #19be6b;
        }
        a {
            font-size: 13px;
            margin: 0 40px;
        }
        ul {
            width: 95%;
            margin: 20px auto;
            font-size: 12px;
            li {
                line-height: 25px;
                text-align: center;
                label {
                    margin-right: 8px;
                }
                span {
                    color: #333;
                }
            }
        }
    }
</style>